package com.arrogames.blondbattle.game.graphics 
{
	import com.arrogames.blondbattle.game.combat.Health;
	import com.arrogames.util.Observable;
	import com.arrogames.util.Observer;
	import flash.display.BitmapData;
	import flash.display.Shape;
	import starling.display.Image;
	import starling.display.Sprite;
	import starling.textures.Texture;
	
	/**
	 * ...
	 * @author ...
	 */
	public class HealthBar extends Sprite implements Observer {
		
		
		private var health:Health;
		private var maxHealth:Number;
		private var fillShape:Image;
		
		public function HealthBar(width:Number, height:Number, health:Health) {
			super();
			
			this.maxHealth = health.value;
			this.health = health;
			this.health.addObserver(this);
			
			var borderThickness:Number = 2;
			
			this.fillShape = createFill(width, height, borderThickness);
			addChild(fillShape);
			addChild(createBorder(width, height, borderThickness));
			
			this.width = width; 
			this.height = height;
		}
		
		private function createFill(width:Number, height:Number, borderThickness:Number):Image {
			var shape:Shape = new Shape();
			shape.graphics.beginFill(0x00ff00);
			shape.graphics.drawRect(0, 0, width, height);
			var bitmapData : BitmapData = new BitmapData( width, height, true, 0 );
			bitmapData.draw( shape, null, null, null, null, true );
			var fillTexture : Texture = Texture.fromBitmapData( bitmapData, false, false, 1 );
			return new Image(fillTexture);
		}
		
		private function createBorder(width:Number, height:Number, borderThickness:Number):Image {
			var shape:Shape = new Shape();
			shape.graphics.lineStyle(borderThickness, 0x000);
			shape.graphics.drawRect(0, 0, width, height);
			var bitmapData : BitmapData = new BitmapData( width, height, true, 0 );
			bitmapData.draw( shape, null, null, null, null, true );
			var borderTexture : Texture = Texture.fromBitmapData( bitmapData, false, false, 1 );
			return new Image(borderTexture);
		}
		
		private function updateFill(value:Number):void {
			if (fillShape) {
				fillShape.width = this.width * value / maxHealth;
			}
		}
		
		override public function dispose():void {
			super.dispose();
			health.deleteObserver(this);
			health = null;
		}
		
		/* INTERFACE com.arrogames.util.Observer */
		public function update(obs:Observable, obj:Object):void {
			if (obs == health) {
				updateFill( health.value );
			}
		}
		
	}

}